package 剑指offer_leetcode;

import java.util.ArrayList;

/**
 * JZ29顺时针打印矩阵
 */
public class 剑指Offer29_顺时针打印矩阵 {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix.length==0)
            return new int[0];
        ArrayList<Integer> res = new ArrayList<>();
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int bottom = matrix.length - 1;
        while(left<=right && top<=bottom){
            for(int i=left;i<=right;i++)
                res.add(matrix[top][i]);
            top++;
            if(top>bottom)
                break;
            for(int i=top;i<=bottom;i++)
                res.add(matrix[i][right]);
            right--;
            if(right<left)
                break;
            for(int i=right;i>=left;i--)
                res.add(matrix[bottom][i]);
            bottom--;
            if(bottom<top)
                break;
            for(int i=bottom;i>=top;i--)
                res.add(matrix[i][left]);
            left++;
            if(left>right)
                break;
        }
        if(res.size()==0)
            return new int[0];
        int[] arr = new int[res.size()];
        for(int i=0;i<res.size();i++)
            arr[i] = res.get(i);
        return arr;
    }
}
